package com.cmcc.groupcontacts.database;

import java.util.ArrayList;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.cmcc.groupcontacts.firewall.dao.model.CallListVO;
import com.cmcc.groupcontacts.firewall.dao.model.FilterListVO;
import com.cmcc.groupcontacts.firewall.dao.model.KeywordsVO;
import com.cmcc.groupcontacts.firewall.dao.model.SmsListVO;
import com.cmcc.groupcontacts.numbersearch.model.NumberCategory;
import com.cmcc.groupcontacts.numbersearch.model.SearchNumber;
import com.cmcc.groupcontacts.util.ExceptionHandler;

/**
 * 数据库创建版本管理器
 * 
 * @author
 * 
 */
public class DatabaseManager extends SQLiteOpenHelper {
	private static final String LOG_TAG = "DatabaseManager";

	public DatabaseManager(Context context, String name, CursorFactory factory,
			int version) {
		super(context, name, factory, version);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		db.execSQL(SmsListVO.MetaData.CREATE_DDL);
		db.execSQL(CallListVO.MetaData.CREATE_DDL);
		db.execSQL(FilterListVO.MetaData.CREATE_DDL);
		db.execSQL(KeywordsVO.MetaData.CREATE_DDL);

		// db.execSQL(Note.MetaData.CREATE_DDL);
		// db.execSQL(NoteCategory.MetaData.CREATE_DDL);
		// db.execSQL(NoteCategory.MetaData.INSERT_DEFAULT);

		db.execSQL(NumberCategory.MetaData.CREATE_DDL);
		for (String s : NumberCategory.MetaData.INSERT_DEFAULT) {
			db.execSQL(s);
		}
		db.execSQL(SearchNumber.MetaData.CREATE_DDL);
		for (String s : SearchNumber.MetaData.INSERT_DEFAULT) {
			db.execSQL(s);
		}

		release();
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		ArrayList<String> updateSql;
		Log.v(LOG_TAG, "旧版本：" + oldVersion + "，当前版本：" + newVersion);
		for (int i = oldVersion + 1; i <= newVersion; i++) {
			if ((updateSql = DatabaseChangeLogManager.getChangeLog(i)) != null) {
				for (String sql : updateSql) {
					try {
						db.execSQL(sql);
					} catch (SQLException e) {
						ExceptionHandler.handleAcceptable(e, "数据库升级执行出错，版本号："
								+ i);
					}
				}
			}
		}

		release();
	}

	private void release() {
		DatabaseChangeLogManager.clearData();

		SmsListVO.MetaData.CREATE_DDL = null;
		CallListVO.MetaData.CREATE_DDL = null;
		FilterListVO.MetaData.CREATE_DDL = null;
		KeywordsVO.MetaData.CREATE_DDL = null;
		//
		// Note.MetaData.CREATE_DDL = null;
		// NoteCategory.MetaData.CREATE_DDL = null;
	}
}
